import {
	BASE_URL,
	HEADER,
	TOKENNAME,
	PYTHON_URL,
} from '@/config/request.js';
import store from '@/store';

/**
 * 发送请求
 * @param {String} url 请求api 
 * @param {String} method 请求方式
 * @param {Object} data 请求体内容  
 * @example baseRequest('api/api', 'post', config)
 */
function baseRequest(url, method, data, config = {}) {
	let header = {
		...HEADER,
		// 'content-type': 'multipart/form-data'
	}
	let param = {
		...data,
	}
	// if (store.getters('token')) header.token = store.getters('token');
	if (store.state.user.userInfo) {
		header.user_id = store.state.user.userInfo.user_id
		param.user_id = store.state.user.userInfo.user_id
	}
	return new Promise((reslove, reject) => {
		uni.request({
			url: config.isPython ? PYTHON_URL + url : BASE_URL + url,
			method: method || 'GET',
			header,
			data: param,
			success: (res) => {
				if (res.data.status === 1 || res.data.status === 200 || res.data.code === 200) {
					reslove(res.data, res);
				} else reject(res.data.msg || res.data || '系统错误');
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect']
.forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});

export default request;